package com.common.config;

import com.common.secuity.filter.JwtAuthenticationTokenFilter;
import com.common.service.TokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security 权限配置
 * 配置安全过滤器链、密码编码器和认证管理器
 *
 * @author LY
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    @Autowired
    private TokenService tokenService;


    /**
     * 身份验证实现
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 配置请求授权
        configureAuthorization(http);

        // 配置会话管理为无状态
        http.sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        // 禁用 CSRF
        http.csrf(AbstractHttpConfigurer::disable);

        // 添加自定义过滤器
        addCustomFilters(http);

        return http.build();
    }

    /**
     * 配置HttpSecurity以设置授权规则
     * 此方法定义了哪些请求可以被所有用户访问（无需认证），哪些请求需要用户认证后才能访问
     *
     * @param http HttpSecurity实例，用于配置Web安全
     * @throws Exception 配置过程中可能抛出的异常
     */
    private void configureAuthorization(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(requestMatcherRegistry ->
                requestMatcherRegistry
                        .requestMatchers("/auth/login").permitAll()
                        .requestMatchers("/webHook/**").permitAll()
                        .requestMatchers(
                                "/webjars/**",
                                "/doc.html",
                                "/swagger-resources/**",
                                "/v3/api-docs/**",
                                "/swagger-ui/**",
                                "/swagger-ui.html",
                                "/ws/**",
                                "/ws-app/**")
                        .permitAll()
                        .anyRequest().authenticated()
        );
    }

    /**
     * 在UsernamePasswordAuthenticationFilter之前添加JWT验证过滤器
     * 添加自定义过滤器到HttpSecurity中
     */
    private void addCustomFilters(HttpSecurity http) {
        http.addFilterBefore(new JwtAuthenticationTokenFilter(tokenService), UsernamePasswordAuthenticationFilter.class);
    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
